package com.app.zhuozhuo

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception
import java.lang.ref.WeakReference

private val TAG = MainActivity::class.java.simpleName

class MainActivity : AppCompatActivity() {

    private val listData = mutableListOf(
        ListItemEntity("https://sspai.com/post/44735", false),
        ListItemEntity("https://sspai.com/post/44667", false),
        ListItemEntity("https://sspai.com/post/44776", false),
        ListItemEntity("https://sspai.com/post/44759", false),
        ListItemEntity("https://sspai.com/post/44775", false),
        ListItemEntity("https://sspai.com/post/44738", false),
        ListItemEntity("https://sspai.com/post/44669", false),
        ListItemEntity("https://sspai.com/post/44710", false),
        ListItemEntity("https://sspai.com/post/44748", false),
        ListItemEntity("https://sspai.com/post/44763", false),
        ListItemEntity("https://sspai.com/post/44715", false),
        ListItemEntity("https://sspai.com/post/44692", false),
        ListItemEntity("https://sspai.com/post/44751", false),
        ListItemEntity("https://sspai.com/post/44706", false),
        ListItemEntity("https://sspai.com/post/44693", false),
        ListItemEntity("https://sspai.com/post/44745", false),
        ListItemEntity("https://sspai.com/post/44720", false),
        ListItemEntity("https://sspai.com/post/44688", false),
        ListItemEntity("https://sspai.com/post/44723", false),
        ListItemEntity("https://sspai.com/post/44728", false),
        ListItemEntity("https://sspai.com/post/44654", false),
        ListItemEntity("https://sspai.com/post/44714", false),
        ListItemEntity("https://sspai.com/post/44716", false),
        ListItemEntity("https://sspai.com/post/44701", false),
        ListItemEntity("https://sspai.com/post/44687", false),
        ListItemEntity("https://sspai.com/post/44681", false),
        ListItemEntity("https://sspai.com/post/44702", false),
        ListItemEntity("https://sspai.com/post/44653", false),
        ListItemEntity("https://sspai.com/post/44656", false),
        ListItemEntity("https://sspai.com/post/44683", false),
        ListItemEntity("https://sspai.com/post/44668", false),
        ListItemEntity("https://sspai.com/post/44647", false)
    )


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val listAdapter = ListAdapter(this, listData)

        activity_main_list.layoutManager = LinearLayoutManager(this)

        activity_main_list.adapter = listAdapter

        activity_main_list.addOnScrollListener(onScrollListener)

    }

    override fun onResume() {
        super.onResume()
        WebViewFactory_StartPreload()
    }

    override fun onPause() {
        super.onPause()
        WebViewFactory_StopPreload()
    }

    private val onScrollListener = object: RecyclerView.OnScrollListener() {

        @Volatile
        private var isScroll = false

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            when(newState) {
                RecyclerView.SCROLL_STATE_IDLE -> {
                    Log.i(TAG, "MainActivity --> onScrollListener --> onScrollStateChanged --> SCROLL_STATE_IDLE")
                    isScroll = false
                    WebViewFactory_StartPreload()
                    dispatchScrollStatus(ScrollState.STATIC)

                }
                RecyclerView.SCROLL_STATE_DRAGGING, RecyclerView.SCROLL_STATE_SETTLING  -> {
                    Log.i(TAG, "MainActivity --> onScrollListener --> onScrollStateChanged --> SCROLL_STATE_DRAGGING")
                    if (!isScroll) {
                        isScroll = true
                        WebViewFactory_StopPreload()
                        dispatchScrollStatus(ScrollState.SCROLLING)
                    }
                }
            }
        }
    }

}

enum class ScrollState {
    SCROLLING, STATIC
}

interface ScrollStatusListener {

    fun notifyState(scrollState: ScrollState)

}

private val scrollStatusListeners = mutableListOf<ScrollStatusListener>()
/**
 * 分发滚动事件
 */
private fun dispatchScrollStatus(scrollState: ScrollState) {
    for (item in scrollStatusListeners) {
        item.notifyState(scrollState)
    }
}

data class ListItemEntity(var url: String, var isLoadFinished: Boolean)

private const val HANDLER_CODE = 1

class ItemView(context: Context): RelativeLayout(context), ScrollStatusListener, View.OnClickListener, PreloadResultListener {

    private var itemEntity: ListItemEntity? = null

    private var itemHandler: ItemHandler? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.activity_main_list_item, this)
        setOnClickListener(this)
    }

    private val urlTextView = findViewById<TextView>(R.id.activity_main_list_item_url)
    private val statusTextView = findViewById<TextView>(R.id.activity_main_list_item_status)

    fun bindData(itemEntity: ListItemEntity) {
        this.itemEntity = itemEntity
    }

    fun updateViewData() {

        try {
            urlTextView.text = itemEntity?.url

            itemEntity?.let {
                if (it.isLoadFinished) {
                    statusTextView.visibility = View.VISIBLE
                } else {
                    statusTextView.visibility = View.GONE
                }
            }

        } catch (ex: Exception) {
            ex.printStackTrace()
        }

    }

    override fun onClick(v: View?) {

        Log.i(TAG, "onClick --> url --> ${itemEntity?.url}")

        itemEntity?.url?.let {
            Log.i(TAG, "onClick ---> let --> url --> $it")
            WebActivity_instance(context, it)
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        Log.i(TAG, "onAttachedToWindow")
        itemHandler = ItemHandler(this)
        scrollStatusListeners.add(this)
        itemEntity?.url?.let {
            WebViewFactory_addPreloadResultListener(this, it)
        }

        itemEntity?.isLoadFinished?.let { it ->
            if (!it) {
                itemHandler?.let {it1 ->
                    if (!it1.hasMessages(HANDLER_CODE)) {
                        it1.sendEmptyMessageDelayed(HANDLER_CODE, 3000)
                    }
                }
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        itemHandler?.removeCallbacksAndMessages(null)
        itemHandler = null
        scrollStatusListeners.remove(this)
        itemEntity?.url?.let {
            WebViewFactory_removePreloadResultListener(it)
        }
    }

    override fun notifyState(scrollState: ScrollState) {
        itemEntity?.isLoadFinished?.let {
            if (it) {
                return
            }
        }
        when(scrollState) {
            ScrollState.SCROLLING -> {
                itemHandler?.removeMessages(HANDLER_CODE)
            }
            ScrollState.STATIC -> {
                itemHandler?.let {
                    if (!it.hasMessages(HANDLER_CODE)) {
                        it.sendEmptyMessageDelayed(HANDLER_CODE, 3000)
                    }
                }
            }
        }
    }

    /**
     * 调用预加载函数
     */
    fun preloadUrl() {

        itemEntity?.url?.let {
            WebViewFactory_load(it, true)
        }
    }

    override fun onPreloadFinished() {
        itemEntity?.isLoadFinished = true

        statusTextView.visibility = View.VISIBLE


    }

    class ItemHandler(view: ItemView) : Handler() {

        private val weakReference = WeakReference<ItemView>(view)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what) {
                HANDLER_CODE -> {
                    weakReference.get()?.preloadUrl()
                }
            }
        }
    }

}

class ListAdapter(private val context: Context, private val data: MutableList<ListItemEntity>) : RecyclerView.Adapter<ListAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = ItemView(context)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int = data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        try {
            val itemData = data[position]
            holder.view.bindData(itemData)
            holder.view.updateViewData()
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }


    inner class ViewHolder(val view: ItemView) : RecyclerView.ViewHolder(view)
}
